<?php

namespace App\Http\Controllers\Auth;

use App\Models\CompanyProfile;
use App\Models\Member;
use App\Models\Resume;
use App\Models\SmsQueue;

use App\Http\Controllers\Core\Controller;
use Exception;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Session;
use Overtrue\EasySms\EasySms;

class RegisterController extends Controller
{
    public function __construct()
    {
//        $this->middleware('guest');
    }

    /**
     * ajax 返回验证模块
     */
    public function ajax()
    {
        $data['html'] = view('modal.register')->render();
        return json_encode(['data' => $data]);
    }

    /**
     * 验证手机号是否已经注册
     * @param Request $request
     * @return false|string
     */
    public function check(Request $request)
    {
        $param = $request->get('param');
        $member = Member::where(['mobile' => $param])->get();
        if ($member->first()) {
            return json_encode(['data' => '', 'msg' => '账号已经存在', 'status' => 0]);
        }
        return json_encode(['data' => '', 'msg' => '成功', 'status' => 1]);
    }

    var $config = [
        // HTTP 请求的超时时间（秒）
        'timeout' => 5.0,
        // 默认发送配置
        'default' => [
            // 网关调用策略，默认：顺序调用
            'strategy' => \Overtrue\EasySms\Strategies\OrderStrategy::class,

            // 默认可用的发送网关
            'gateways' => [
                'yunpian', 'aliyun',
            ],
        ],
        // 可用的网关配置
        'gateways' => [
            'errorlog' => [
                'file' => '/tmp/easy-sms.log',
            ],
            'yunpian' => [
                'api_key' => '824f0ff2f71cab52936axxxxxxxxxx',
            ],
            'aliyun' => [
                'access_key_id' => 'LTAIIvNgzvoH6ed9',
                'access_key_secret' => '6ncTnF1tdefdRiof6Eqh62gM3q1103',
                'sign_name' => '杭州山姆消防培训学校',
            ]
        ],
    ];

    /**
     * 验证规则
     * @param $value
     * @param $rule
     * @return bool
     */
    function fieldRegex($value, $rule)
    {
        $validate = array(
            'require' => '/.+/',
            'email' => '/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/',
            'mobile' => '/^(13|15|14|16|17|18|19)\d{9}$/',
            'tel' => '/^(([0\\+]\\d{2,3}-)?(0\\d{2,3})-)?(\\d{7,8})(-(\\d{3,}))?$/',
            'url' => '/^http(s?):\/\/(?:[A-za-z0-9-]+\.)+[A-za-z]{2,4}(?:[\/\?#][\/=\?%\-&~`@[\]\':+!\.#\w]*)?$/',
            'currency' => '/^\d+(\.\d+)?$/',
            'number' => '/^\d+$/',
            'zip' => '/^\d{6}$/',
            'integer' => '/^[-\+]?\d+$/',
            'double' => '/^[-\+]?\d+(\.\d+)?$/',
            'english' => '/^[A-Za-z]+$/',
            'img' => '(.*)\\.(jpg|bmp|gif|ico|pcx|jpeg|tif|png|raw|tga)$/',
            'in' => '/^(\d{1,10},)*(\d{1,10})$/',
            'qq' => '/^[1-9]*[1-9][0-9]*$/'
        );
        // 检查是否有内置的正则表达式
        if (isset($validate[strtolower($rule)]))
            $rule = $validate[strtolower($rule)];
        return preg_match($rule, $value) === 1;
    }

    /**
     * 发送验证码
     * @param Request $request
     * @return false|string
     */
    public function sms(Request $request)
    {
        $mobile = $request->get('mobile');
        $code = rand(1000, 9999);
        //手机号码验证
        if (!$this->fieldRegex($mobile, 'mobile')) {
            return json_encode(['data' => '', 'msg' => '手机格式错误', 'status' => 0]);
        }
        //判断上一次验证是否超过180秒
        $queue = SmsQueue::where(['mobile' => $mobile])->orderBy('id', 'desc')->get();
        $now = time();
        $queue = $queue->first();
        if ($queue && $now < ($queue->time + 180)) {
            return json_encode(['data' => '', 'msg' => '180秒内仅能获取一次短信验证码,请稍后重试', 'status' => 0]);
        }
        //插入数据
        $smsQueue = new SmsQueue();
        $smsQueue->code = $code;
        $smsQueue->time = $now;
        $smsQueue->mobile = $mobile;
        if ($smsQueue->save()) {
            $easySms = new EasySms($this->config);
            $easySms->send($mobile, [
                'content' => '您的验证码为: ' . $code,
                'template' => 'SMS_153960151',
                'data' => [
                    'code' => $code
                ],
            ]);
            //插入数据库
            return json_encode(['data' => '', 'msg' => '成功', 'status' => 1]);
        } else {
            return json_encode(['data' => '', 'msg' => '短信发送失败，请稍后尝试', 'status' => 0]);
        }
    }

    /**
     * 新增用户
     * @param Request $request
     * @return false|string
     */
    public function add(Request $request)
    {

        $mobile = $request->get('mobile');
        $code = $request->get('mobile_code');
        $type = $request->get('type');
        $company_name = $request->get('company_name');
        $contact = $request->get('contact');
        $password = $request->get('password');
        $passwordVerify = $request->get('passwordVerify');

        if (!$this->fieldRegex($mobile, 'mobile')) {
            return json_encode(['data' => '', 'msg' => '手机格式错误', 'status' => 0]);
        }
        $member = Member::where(['mobile' => $mobile])->get();
        if ($member->first()) {
            return json_encode(['data' => '', 'msg' => '账号已经存在', 'status' => 0]);
        }
        //获取最近的code
        $queue = SmsQueue::where(['mobile' => $mobile, 'status' => 1])->orderBy('time', 'Desc')->get();

        if (!$queue = $queue->first()) {
            return json_encode(['data' => '', 'msg' => '请再次发送验证码', 'status' => 0]);
        }

        if ($queue->code != $code) {
            return json_encode(['data' => '', 'msg' => '验证码错误', 'status' => 0]);
        }
        if ($password != $passwordVerify) {
            return json_encode(['data' => '', 'msg' => '两次密码不同', 'status' => 0]);
        }
        $ip = $request->getClientIp();
        $time = time();

        DB::beginTransaction();
        $member = $this->createMember($mobile, $type, $contact, $password, $time, $ip);
        if (!$member) {
            DB::rollBack();
            return json_encode(['data' => '', 'msg' => '数据写入失败，请刷新后尝试', 'status' => 0]);
        }
        //公司用户注册
        if ($mobile && $type == 1) {
            $more = CompanyProfile::Create([
                'user_id' => $member->id,
                'name' => $company_name,
                'contact' => $contact,
                'telephone' => $mobile
            ]);
        } elseif ($mobile && $type == 2) {
            //个人用户创建简历
            $more = Resume::Create([
                'user_id' => $member->id,
                'nickname' => $member->nickname,
                'telephone' => $mobile,
                'create_time' => $time,
                'refresh_time' => $time
            ]);
        } else {
            $more = false;
        }
        if (!$more) {
            DB::rollBack();
            return json_encode(['data' => '', 'msg' => '数据写入失败，请刷新后尝试', 'status' => 0]);
        }
        DB::commit();
        //模拟登录
        session::put('member', $member);
        if ($type == 1) {
            $url = url('/company/info');
        } else if ($type == 2) {
            $url = url('/member');
        } else {
            return json_encode(['data' => '', 'msg' => '登陆失败', 'status' => 0]);
        }
        return json_encode(['data' => ['url' => $url], 'msg' => '成功', 'status' => 1]);
    }

    /**
     * 创建用户信息
     * @param $mobile
     * @param $type
     * @param $contact
     * @param $password
     * @param $time
     * @param $ip
     * @return
     */
    public function createMember($mobile, $type, $contact, $password, $time, $ip)
    {
        $member = Member::create([
            'username' => $mobile,
            'type' => $type,
            'nickname' => $contact ? $contact : '',
            'mobile' => $mobile,
            'password' => md5($password),
            'reg_time' => $time,
            'reg_ip' => $ip,
            'last_login_time' => $time,
            'last_login_ip' => $ip
        ]);
        return $member;
    }

    public function resetPassword()
    {
        return view('auth.passwords.reset');
    }
}
